import React, { useState } from 'react';
import { Card, Button, Descriptions, Tag, Modal, Form, Input, message, Popconfirm } from 'antd';
import { UserOutlined, StarOutlined, BookOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import { Character, CharacterUpdate } from '../types';
import characterService from '../services/characterService';

interface CharacterDetailProps {
  character: Character;
  onStartConversation: () => void;
  onBack: () => void;
}

const CharacterDetail: React.FC<CharacterDetailProps> = ({ 
  character, 
  onStartConversation, 
  onBack 
}) => {
  const [isEditModalVisible, setIsEditModalVisible] = useState<boolean>(false);
  const [form] = Form.useForm();
  const [isSubmitting, setIsSubmitting] = useState<boolean>(false);
  const [isDeleting, setIsDeleting] = useState<boolean>(false);

  // 显示编辑角色模态框
  const showEditModal = () => {
    // 将当前角色数据填充到表单中
    form.setFieldsValue({
      name: character.name,
      description: character.description,
      background: character.background,
      language: character.language.join(','),
      personality: character.personality.join(','),
      skills: character.skills.map(skill => `${skill.name}:${skill.description}`).join(';')
    });
    setIsEditModalVisible(true);
  };

  // 隐藏编辑角色模态框
  const handleCancel = () => {
    setIsEditModalVisible(false);
    form.resetFields();
  };

  // 编辑角色提交
  const handleEditSubmit = async (values: any) => {
    setIsSubmitting(true);
    try {
      // 构建CharacterUpdate对象
      const updateData: CharacterUpdate = {};
      
      // 只包含有值的字段
      if (values.name && values.name.trim() !== character.name) {
        updateData.name = values.name.trim();
      }
      if (values.description && values.description.trim() !== character.description) {
        updateData.description = values.description.trim();
      }
      if (values.background && values.background.trim() !== character.background) {
        updateData.background = values.background.trim();
      }
      if (values.language) {
        const languages = values.language.split(',').map((lang: string) => lang.trim()).filter((lang: string) => lang);
        if (languages.length > 0 && JSON.stringify(languages) !== JSON.stringify(character.language)) {
          updateData.language = languages;
        }
      }
      if (values.personality) {
        const personality = values.personality.split(',').map((trait: string) => trait.trim()).filter((trait: string) => trait);
        if (personality.length > 0 && JSON.stringify(personality) !== JSON.stringify(character.personality)) {
          updateData.personality = personality;
        }
      }
    

      // 如果有字段需要更新，则调用更新方法
      if (Object.keys(updateData).length > 0) {
        await characterService.updateCharacter(character.id, updateData);
        
        // 刷新当前页面数据
        window.location.reload();
        message.success('角色更新成功！');
      } else {
        message.info('没有任何更改');
      }
      
      setIsEditModalVisible(false);
      form.resetFields();
    } catch (error) {
      console.error('更新角色失败:', error);
      message.error('更新角色失败，请重试');
    } finally {
      setIsSubmitting(false);
    }
  };

  // 删除角色
  const handleDeleteCharacter = async () => {
    setIsDeleting(true);
    try {
      await characterService.deleteCharacter(character.id);
      message.success('角色删除成功！');
      // 删除成功后返回搜索页面
      onBack();
    } catch (error) {
      console.error('删除角色失败:', error);
      message.error('删除角色失败，请重试');
    } finally {
      setIsDeleting(false);
    }
  };

  return (
    <div style={{ padding: '20px', maxWidth: '1000px', margin: '0 auto' }}>
      <Button 
        type="default" 
        icon={<BookOutlined />} 
        onClick={onBack} 
        style={{ marginBottom: '20px' }}
      >
        返回搜索
      </Button>

      <Card 
        title={
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <div>
              <span style={{ fontSize: '24px', fontWeight: 'bold' }}>{character.name}</span>
              <span style={{ marginLeft: '15px', color: '#8c8c8c', fontSize: '18px' }}>
                ({character.nameEn})
              </span>
            </div>
            <div style={{ display: 'flex', gap: '10px' }}>
              <Button 
                type="primary" 
                size="large" 
                onClick={onStartConversation}
                icon={<StarOutlined />}
              >
                开始对话
              </Button>
              <Button 
                type="default" 
                size="large" 
                onClick={showEditModal}
                icon={<EditOutlined />}
              >
                编辑角色
              </Button>
              <Popconfirm
                title="确认删除角色"
                description={`确定要删除角色 "${character.name}" 吗？此操作将级联删除所有相关数据，且无法恢复。`}
                onConfirm={handleDeleteCharacter}
                okText="确定"
                cancelText="取消"
                okButtonProps={{ danger: true }}
              >
                <Button 
                  type="default" 
                  danger
                  size="large" 
                  icon={<DeleteOutlined />}
                  loading={isDeleting}
                >
                  删除角色
                </Button>
              </Popconfirm>
            </div>
          </div>
        }
        style={{ marginBottom: '20px' }}
      >
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: '30px' }}>
          {/* 左侧头像区域 */}
          <div style={{ flex: '0 0 auto' }}>
            <div style={{ 
              width: '200px', 
              height: '200px', 
              borderRadius: '50%', 
              overflow: 'hidden', 
              marginBottom: '20px',
              border: '5px solid #1890ff'
            }}>
              <img 
                src={character.avatar} 
                alt={character.name} 
                style={{ width: '100%', height: '100%', objectFit: 'cover' }}
              />
            </div>
          </div>

          {/* 右侧信息区域 */}
          <div style={{ flex: '1 1 400px' }}>
            <Descriptions column={1} bordered>
              <Descriptions.Item label="简介">{character.description}</Descriptions.Item>
              <Descriptions.Item label="语言能力">
                <div>
                  {character.language.map((lang, index) => (
                    <Tag key={index} color="green" style={{ margin: '2px', fontSize: '14px' }}>
                      {lang}
                    </Tag>
                  ))}
                </div>
              </Descriptions.Item>
              <Descriptions.Item label="性格特点">
                <div>
                  {character.personality.map((trait, index) => (
                    <Tag key={index} color="blue" style={{ margin: '2px', fontSize: '14px' }}>
                      {trait}
                    </Tag>
                  ))}
                </div>
              </Descriptions.Item>
            </Descriptions>
          </div>
        </div>
      </Card>

      {/* 背景故事卡片 */}
      <Card 
        title={
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <UserOutlined style={{ marginRight: '8px' }} />
            背景故事
          </div>
        }
        style={{ marginBottom: '20px' }}
      >
        <p style={{ lineHeight: '1.8', fontSize: '16px' }}>{character.background}</p>
      </Card>

      

      {/* 编辑角色模态框 */}
      <Modal
        title="编辑角色"
        open={isEditModalVisible}
        onCancel={handleCancel}
        footer={null}
        width={700}
        confirmLoading={isSubmitting}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleEditSubmit}
        >
          <Form.Item
            label="角色名称"
            name="name"
          >
            <Input placeholder="例如：哈利波特" />
          </Form.Item>
          
          <Form.Item
            label="角色简介"
            name="description"
          >
            <Input.TextArea rows={2} placeholder="简要描述这个角色" />
          </Form.Item>
          
          <Form.Item
            label="角色背景"
            name="background"
          >
            <Input.TextArea rows={3} placeholder="详细描述角色的背景故事" />
          </Form.Item>
          
          <Form.Item
            label="语言能力（用逗号分隔）"
            name="language"
          >
            <Input placeholder="例如：中文,英文,日文" />
          </Form.Item>
          
          <Form.Item
            label="性格特点（用逗号分隔）"
            name="personality"
          >
            <Input placeholder="例如：勇敢,善良,聪明" />
          </Form.Item>
          
          
          
          <div style={{ textAlign: 'center', marginTop: '20px' }}>
            <Button type="default" onClick={handleCancel} style={{ marginRight: '10px' }}>取消</Button>
            <Button type="primary" htmlType="submit" loading={isSubmitting}>更新角色</Button>
          </div>
        </Form>
      </Modal>
    </div>
  );
};

export default CharacterDetail;